/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Animation;

import Animation.Animation;
import java.util.LinkedList;
import Scenery.BaseSprite;
import java.util.ArrayList;
import java.util.List;

/*
 * 
 * @author: Ziden
 * 
 */

public class BaseSpriteAnimation {
    
    public BaseSpriteAnimation(BaseSprite body) {
        animationBody = body;
    }
    
    private List<Animation> animations = new ArrayList<Animation>();
    private List<Integer> playng = new ArrayList<Integer>();
    private BaseSprite animationBody;
    
    public void addAnimation(Animation anim) {
        animations.add(anim);
    }
    
    public void tick() {
        Integer removed = null;
        if(playng.size() > 0) {
            for(Integer i : playng) {
                animations.get(i).perform();
                if(animations.get(i).canceled) {
                    //animations.get(i).initialState();
                    removed = new Integer(i);
                }
            }
        }
        if(removed!=null) { 
            stopAnimation(animations.get(removed).getName());
        }
    }
    
    public boolean isAnimationPlayng(String name) {
        for(Animation anim : animations) {
            if(anim.getName().equalsIgnoreCase(name)) {
                Integer index = new Integer(animations.indexOf(anim));
                if(playng.contains(index)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public void playAnimation(String name) {
        for(Animation anim : animations) {
            if(anim.getName().equalsIgnoreCase(name)) {
                Integer index = new Integer(animations.indexOf(anim));
                if(anim.canceled && playng.contains(index)) {
                    playng.remove(index);
                }
                if(!playng.contains(index)) {
                    anim.gotoInitialState();
                    anim.saveInitialState();
                    playng.add(index);
                }
            }
        }
    }
    
    public void stopAnimation(String name) {
        Animation anim = getAnimation(name);
        Integer index = animations.indexOf(anim);
        if(playng.contains(index)) {
            anim.gotoInitialState();
            playng.remove(index);
        }
    }
    
    public void setAnimationParameter(String anim, Object p) {
        getAnimation(anim).setParameter(p);
    }
    
    public Animation getAnimation(String name) {
        for(Animation an : animations) {
            if(an.getName().equalsIgnoreCase(name))
                    return an;
        }
        return null;
    }
}
